import React, { useEffect, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { isEmpty } from '@/utils/common';
import useDebounceFn from '@/utils/useDebounceFn';
import { Mask, ModalWrap, AsyncLoading } from '@/design';
import { queryLoveCode } from '@/services/order'
import { useSelector, useDispatch } from 'umi';

import styles from '../../checkorder/checkorder.less';

// 預定信息
export default function (props: any) {
  const { loveVisiable, onClose, onClickSure } = props;
  let unmount = false;

  const [loveCodes, setLoveCodes] = useState([]);
  const [searchCode, setSearchCode] = useState([]);

  useEffect(() => {
    if (isEmpty(loveCodes)) {
      fetchLoveCode();
    }
    return () => {
      unmount = true;
    }
  }, [])
  
  const { run: filterCodes } = useDebounceFn((value:any) => {
    let newCodes = [];
    if (!isEmpty(value)) {
      loveCodes.forEach((item:any) => {
        if (item.loveCode.indexOf(value) > -1 || item.name.indexOf(value) > -1) {
          newCodes.push(item);
        }
      })
    } else {
      newCodes = JSON.parse(JSON.stringify(loveCodes))
    }
    setSearchCode(newCodes)
  }, 300)

  /* 查詢愛心碼列表 */
  const fetchLoveCode = async () => {
    let result = await queryLoveCode();
    if (unmount || !result) return;
    setLoveCodes(result.data);
    setSearchCode(result.data);
  }

  /* 遍歷愛心碼 */
  const handleSearchCode = (event:any) => {
    let value = event.target.value;
    filterCodes(value)
  }

  /* 選擇愛心碼 */
  const handleSelect = (code:any) => {
    props.onChange(code);
    props.onClose();
  }

  return (<ModalWrap headName={'選擇捐贈碼'} modalVisiable={loveVisiable} onClose={onClose} onClickSure={onClickSure}>
    {isEmpty(loveCodes) ? <AsyncLoading/> : <div className={styles.love_wrap}>
      <div className={styles.search}>
        <input type="text" placeholder="請輸入【捐贈碼/機構名稱】查詢" onChange={handleSearchCode} />
      </div>
      <ul className={styles.list}>
        {searchCode.map((item:any) => (
          <li key={item.loveCode} onClick={() => { handleSelect(item.loveCode) }}>
            <p className={styles.code}>{item.loveCode}</p>
            <p className={styles.name}>{item.name}</p>
          </li>
        ))}
      </ul>
    </div>}
    
  </ModalWrap>
  )
}